package com.biz.primus.ms.commodity.dao.specification;

import com.biz.primus.base.enums.ExtendType;
import com.biz.primus.commodity.vo.ExtendQueryVo;
import com.biz.primus.ms.commodity.dao.po.Extend;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

public class ExtendSpecification implements Specification<Extend> {

    private ExtendQueryVo reqVo;

    public ExtendSpecification(ExtendQueryVo extendQueryVo) {
        this.reqVo = extendQueryVo;
    }

    @Override
    public Predicate toPredicate(Root<Extend> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = Lists.newArrayList();
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTimestamp")));
        if (StringUtils.isNotBlank(reqVo.getCategoryId())){
            Predicate predicate = criteriaBuilder.equal(root.get("categoryId").as(Long.class), Long.valueOf(reqVo.getCategoryId()));
            predicates.add(predicate);

        }
        if (reqVo.getExtendType() != null) {
            Predicate predicate = criteriaBuilder.equal(root.get("extendType").as(ExtendType.class), reqVo.getExtendType());
            predicates.add(predicate);
        }
        if (StringUtils.isNotBlank(reqVo.getLabel())){
            Predicate predicate = criteriaBuilder.equal(root.get("label").as(String.class), reqVo.getLabel());
            predicates.add(predicate);
        }
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        return criteriaQuery.getRestriction();
    }
}
